﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.MediaPlayer.Interop;
using BMproductions.Media.MediaPlayer.WMPPlus.Properties;

namespace BMproductions.Media.MediaPlayer.WMPPlus {
	public partial class SettingsForm: Form {
		#region private fields
		private enum PersistAction { Load, Save }

		private WMPPlusSettings settings = null;
		//private WMPPlusCore core;
		private IWMPCore wmp;
		private bool loading = false;
		private IDictionary<TabPage, string> tabLabes = new Dictionary<TabPage, string>();
		private TabPage[] tabs;
		private TabControl singlePage;
		#endregion

		#region Constructors
		private void InitializeSinglePage() {
			singlePage = new TabControl();
			singlePage.SuspendLayout();
			singlePage.Location = Pages.Location;
			singlePage.Size = Pages.Size;
			singlePage.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
			singlePage.ItemSize = new Size(Application.RenderWithVisualStyles ? Pages.Width - 6 : Pages.Width - 4, 6);
			singlePage.SizeMode = TabSizeMode.Fixed;
			//SelectPage(Pages.TabPages[0]);
			lvPages.Items[0].Selected = true;
			Pages.Visible = false;
			singlePage.Visible = true;
			this.Controls.Add(singlePage);
			singlePage.ResumeLayout();
		}

		public SettingsForm() {
			InitializeComponent();

			//lvPages.DoubleBuffered = false;
			tabLabes.Add(shLibrary, Resources.LibraryTitle);
			tabLabes.Add(shUserInterface, Resources.UserInterfaceTitle);
			tabLabes.Add(shContextMenus, Resources.ContextMenusTitle);
			tabLabes.Add(shRestoreMedia, Resources.RestoreMediaTitle);
			tabLabes.Add(shRestorePlugins, Resources.RestorePluginsTitle);
			tabLabes.Add(shMessenger, Resources.MessengerTitle);
			tabLabes.Add(shAbout, Resources.AboutTitle);

			//core = new WMPPlusCore();

			var info = SystemIcons.Information;
			icoInfo.Image = info.ToBitmap();
			icoInfo2.Image = info.ToBitmap();
			using (var about = new Icon(Resources.app, icoAbout.Size)) {
				icoAbout.Image = about.ToBitmap();
			}

			imgsIcons.Images.AddRange(new Image[]
			{
				Resources.lib.ToBitmap(),
				Resources.ui.ToBitmap(),
				Resources.menu.ToBitmap(),
				Resources.media.ToBitmap(),
				Resources.plugin.ToBitmap(),
				Resources.msn.ToBitmap(),
				Resources.info.ToBitmap(),
			});

			tabs = new TabPage[]
			{
				shLibrary,
				shUserInterface,
				shContextMenus,
				shRestoreMedia,
				shRestorePlugins,
				shMessenger,
				shAbout
			};

			for (int k = 0; k < tabs.Length; k++) {
				var tab = tabs[k];
				if (!tab.CausesValidation)
					continue;
				var item = new ListViewItem(tab.Text, k);
				item.Tag = tab;
				lvPages.Items.Add(item);
			}

			var filever = (System.Reflection.AssemblyFileVersionAttribute[])typeof(SettingsForm).Assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), true);
			var ver = filever == null || filever.Length == 0 ? typeof(SettingsForm).Assembly.GetName().Version.ToString() : filever[0].Version;
			lblVersion.Text = lblVersion.Text.Replace("x.x", ver);

			InitializeSinglePage();
		}
		#endregion

		#region Methods
		public void Init(WMPPlusSettings settings, IWMPCore core) {
			this.settings = settings;
			this.wmp = core;
			if (this.wmp != null && WMPUtils.GetMajorVersion(this.wmp.versionInfo) != 11) {
				this.gbATE.Visible = false;
			}
			foreach (var tab in tabs)
				Persist(PersistAction.Load, tab);
		}

		private void SelectPage(TabPage page) {
			singlePage.SuspendLayout();
			if (singlePage.TabPages.Count > 0)
				Pages.Controls.Add(singlePage.TabPages[0]);
			singlePage.Controls.Add(page);
			page.Text = "";
			lblTitle.Text = tabLabes[page];
			page.Controls.Add(paHeader);
			singlePage.ResumeLayout();
		}

		private void Persist(PersistAction action, TabPage page) {
			loading = true;
			try {
				if (page == shLibrary) {
					PersistCheckbox(WMPPlusSettings.BoolNames.FindAsYouType, chkFindAsYouType, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.DisableGroupHeaders, chkDisableGroupHeaders, action);
				}
				else if (page == shUserInterface) {
					PersistCheckbox(WMPPlusSettings.BoolNames.CurrentMediaInTitle, chkNowPlayingTitle, action);
					if (action == PersistAction.Load)
						chkNowPlayingTitle_Click(this, null);
					if (action == PersistAction.Save)
					{
						string titleFormat = txtTitleFormat.Text.Trim();
						if (titleFormat.IsNullEmpty())
							btnDefaultTitleFormat_Click(this, null);
					}
					PersistTextbox(WMPPlusSettings.StringNames.TaskbarATFString, txtTitleFormat, action);
				}
				else if (page == shContextMenus) {
					PersistCheckbox(WMPPlusSettings.BoolNames.ShowFileMenuItemLibraryPane, chkFileMenuLibrary, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.ShowFileMenuItemListPane, chkFileMenuList, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.ShowTagEditorPlusLibraryPane, chkTagEditorPlusLibrary, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.ShowTagEditorPlusListPane, chkTagEditorPlusList, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.ShowATEInPlaylistView, chkATEInListPane, action);
				}
				else if (page == shRestoreMedia) {
					PersistCheckbox(WMPPlusSettings.BoolNames.RestoreLastPlaylist, chkRestorePlaylist, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.RestoreLastMedia, chkRestoreMedia, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.RestoreLastPlayState, chkRestorePlayState, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.RestoreLastPosition, chkRestorePosition, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.RestorePaused, chkRestorePaused, action);
					PersistSpinbox(WMPPlusSettings.NumberNames.RestorePositionRewind, intRestorePositionRewind, action);
					if (action == PersistAction.Load)
						UpdateRestoreMediaView();
				}
				else if (page == shRestorePlugins) {
					if (action == PersistAction.Load) {
						var settings = WMPPlusCore.RestorePlugins.LoadSettings();
						if (!settings.Enabled)
							rbWMPError.Checked = true;
						else if (settings.NoDialog)
							rbKeepDisabled.Checked = true;
						else
							rbEnhancedError.Checked = true;
					}
					else {
						var settings = WMPPlusCore.RestorePlugins.LoadSettings();
						settings.Enabled = !rbWMPError.Checked;
						if (rbEnhancedError.Checked)
							settings.NoDialog = false;
						else if (rbKeepDisabled.Checked) {
							settings.NoDialog = true;
							settings.Option = PluginRestoreOption.opt0;
						}
						WMPPlusCore.RestorePlugins.SaveSettings(settings);
					}
				}
				else if (page == shMessenger) {
					PersistCheckbox(WMPPlusSettings.BoolNames.MSNEnable, chkEnableMSN, action);
					if (action == PersistAction.Load)
						chkEnableMSN_Click(this, null);
					if (action == PersistAction.Save) {
						string msnFormat = txtMSNFormat.Text.Trim();
						if (msnFormat.IsNullEmpty())
							btnDefaultMSNFormat_Click(this, null);
					}
					PersistTextbox(WMPPlusSettings.StringNames.MSNATFString, txtMSNFormat, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.MSNHideOnPause, chkMSNHidePaused, action);
					PersistCheckbox(WMPPlusSettings.BoolNames.MSNShowVideo, chkMSNShowVideo, action);
				}
			}
			finally {
				loading = false;
			}
		}

		private void PersistCheckbox(WMPPlusSettings.BoolNames key, CheckBox box, PersistAction action) {
			switch (action) {
			case PersistAction.Save:
				settings[key] = box.Checked;
				break;
			case PersistAction.Load:
				box.Checked = settings[key];
				break;
			}
		}

		private void PersistTextbox(WMPPlusSettings.StringNames key, TextBox box, PersistAction action) {
			switch (action) {
			case PersistAction.Save:
				settings[key] = box.Text;
				break;
			case PersistAction.Load:
				box.Text = settings[key];
				break;
			}
		}

		private void PersistSpinbox(WMPPlusSettings.NumberNames key, NumericUpDown box, PersistAction action) {
			switch (action) {
			case PersistAction.Save:
				settings[key] = (int)box.Value;
				break;
			case PersistAction.Load:
				box.Value = (decimal)settings[key];
				break;
			}
		}

		private void UpdateRestoreMediaView() {
			bool b = chkRestorePlaylist.Checked;
			chkRestoreMedia.Enabled = b;
			chkRestorePlayState.Enabled = b = b && chkRestoreMedia.Checked;
			chkRestorePaused.Enabled = b && chkRestorePlayState.Checked;
			chkRestorePosition.Enabled = b = b && chkRestorePlayState.Checked;
			intRestorePositionRewind.Enabled = b && chkRestorePosition.Checked;
		}

		private bool Validate(string text, string message) {
			if (!text.IsNullEmpty())
				return true;
			MessageBox.Show(message, Resources.PluginFriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
			return false;
		}

		public void SelectPage(string page, bool validate) {
			var tab = page != null ? tabs.FirstOrDefault(t => t.Name == page) : tabs[0];
			if (tab == null) return;
			//TODO: validate
			SelectPage(tab);
		}
		#endregion

		#region Events handlers

		private void control_OnChange(object sender, EventArgs e) {
			if (!loading)
				btnApply.Enabled = true;
		}

		private void chkNowPlayingTitle_Click(object sender, EventArgs e) {
			bool b = chkNowPlayingTitle.Checked;
			lblTitleFormat.Enabled = b;
			txtTitleFormat.Enabled = b;
			btnDefaultTitleFormat.Enabled = b;
			btnTitleFormatEditor.Enabled = b;
			control_OnChange(sender, e);
		}

		private void btnDefaultTitleFormat_Click(object sender, EventArgs e) {
			txtTitleFormat.Text = WMPPlusSettings.DefaultTitleFormat[(int)WMPPlusSettings.StringNames.TaskbarATFString];
		}

		private void btnDefaultMSNFormat_Click(object sender, EventArgs e) {
			txtMSNFormat.Text = WMPPlusSettings.DefaultTitleFormat[(int)WMPPlusSettings.StringNames.MSNATFString];
		}

		private void chkRestoreOption_Click(object sender, EventArgs e) {
			if (sender == chkRestorePlaylist && chkRestorePlaylist.Checked) {
				chkRestoreMedia.Checked = true;
				chkRestorePlayState.Checked = true;
				chkRestorePosition.Checked = true;
			}
			UpdateRestoreMediaView();
			control_OnChange(sender, e);
		}

		private void lvPages_SelectedIndexChanged(object sender, EventArgs e) {
			if (lvPages.SelectedItems.Count == 0) return;
			var tab = (TabPage)lvPages.SelectedItems[0].Tag;
			SelectPage(tab);
		}

		private void chkEnableMSN_Click(object sender, EventArgs e) {

		}

		private void btnOK_Click(object sender, EventArgs e) {
			if (btnApply.Enabled)
				btnApply_Click(sender, e);
			Close();
		}

		private void btnApply_Click(object sender, EventArgs e) {
			foreach (var tab in tabs)
				Persist(PersistAction.Save, tab);
			settings.SaveSettings();
			settings.UpdateModules();
			btnApply.Enabled = false;
		}

		private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
			string url = (string)((LinkLabel)sender).Tag;
			System.Diagnostics.Process.Start(url);
		}
		#endregion

		private void txtTitleFormat_Validating(object sender, CancelEventArgs e) {
			e.Cancel = !Validate(txtTitleFormat.Text, "Please enter a format for the title bar text, or click on 'Restore default'.");
		}

		private void txtMSNFormat_Validating(object sender, CancelEventArgs e) {
			e.Cancel = !Validate(txtTitleFormat.Text, "Please enter a format for Messenger's What I'm Listening To, or click on 'Restore default'.");
		}
	}
}
